package com.lenovo.translatetext.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatSpinner;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.translatetext.R;
import com.lenovo.translatetext.api.ApiRetrofit;
import com.lenovo.translatetext.entity.TranslatedInfo;
import com.lenovo.translatetext.utils.MD5;
import com.lenovo.translatetext.utils.SpUtils;
import com.lenovo.translatetext.utils.Utils;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.lenovo.translatetext.Constant.*;

public class TranslateActivity extends AppCompatActivity {
    private static final String TAG = TranslateActivity.class.getSimpleName();
    private Context context;
    @BindView(R.id.from)
    EditText from;
    @BindView(R.id.to)
    TextView to;
    @BindView(R.id.choose_language)
    Button mChooseLanguage;
    @BindView(R.id.sp_translate_way)
    AppCompatSpinner mSpTranslateWay;


    //选择语言
    @OnClick(R.id.choose_language)
    void chooseLanguage() {
        startActivityForResult(new Intent(TranslateActivity.this, ChooseLanguageActivity.class), 1);
    }

    //翻译Text
    @OnClick(R.id.translate)
    void translate() {
        String translateText = from.getText().toString();
        if (translateText.isEmpty()) {
            return;
        }
        Log.d(TAG, "translate: Text---->" + translateText);
        String chosenLanguage = mChooseLanguage.getText().toString();
        if (chosenLanguage.isEmpty() || chosenLanguage.equals(getResources().getString(R.string.choose_language))) {
            Toast.makeText(context, "请选择翻译的语言", Toast.LENGTH_SHORT).show();
            return;
        }
        String toLanguage = null;
        String fromLanguage = "auto";
        switch (SpUtils.getTranslateEngine(this)){
            case BAIDU:
                toLanguage = Utils.getBaiduLanguageList().get(chosenLanguage);
                translateByBaidu(translateText, fromLanguage, toLanguage);
                break;
            case GOOGLE:
                toLanguage = Utils.getGoogleLanguageList().get(chosenLanguage);
                translateByGoogle(translateText,fromLanguage,toLanguage);
                break;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_translate);
        ButterKnife.bind(this);
        context = this.getBaseContext();
        initSpinner();
        SpUtils.setTranslateEngine(TranslateActivity.this,BAIDU);
    }

    public void translateByBaidu(String translateText, String fromLanguage, String toLanguage) {
        String salt = String.valueOf(new Random().nextInt(10000));
        String sign = MD5.getMD5(BAIDU_APP_ID + translateText + salt + KEY);
        //发送请求前需要对文字进行URL Encode,由于Retrofit自带编码并默认开启，所以无需手动编码
        //String text=Utils.urlEncode(translateText);
        Log.d(TAG, "translate: text---->" + translateText);
        Log.d(TAG, "translate: salt---->" + salt);
        Log.d(TAG, "translate: sign---->" + sign);

        ApiRetrofit.getBaiduTranslateApi()
                .getTranslatedText(translateText, fromLanguage, toLanguage, BAIDU_APP_ID, salt, sign)
                .enqueue(new Callback<TranslatedInfo>() {
                    @Override
                    public void onResponse(Call<TranslatedInfo> call, Response<TranslatedInfo> response) {
                        TranslatedInfo info = response.body();
                        Log.d(TAG, "onResponse: ResponseBody--->" + info.toString());
                        String errorCode = info.getError_code();
                        if (errorCode == null) {
                            //打印到界面上
                            to.setText(info.getTrans_result().get(0).getDst());
                        } else {
                            if ("52001".equals(errorCode)) {
                                Toast.makeText(context, "请求超时，请重试", Toast.LENGTH_SHORT).show();
                            } else if ("52002".equals(errorCode)) {
                                Toast.makeText(context, "系统错误，请重试", Toast.LENGTH_SHORT).show();
                            } else if ("52003".equals(errorCode)) {
                                Toast.makeText(context, "未授权用户，请检查您的appid是否正确", Toast.LENGTH_SHORT).show();
                            } else if ("54000".equals(errorCode)) {
                                Toast.makeText(context, "必填参数为空，请检查是否少传参数", Toast.LENGTH_SHORT).show();
                            } else if ("58000".equals(errorCode)) {
                                Toast.makeText(context, "客户端IP非法，请检查您填写的IP地址是否正确可修改您填写的服务器IP地址", Toast.LENGTH_SHORT).show();
                            } else if ("54001".equals(errorCode)) {
                                Toast.makeText(context, "签名错误，请检查您的签名生成方法", Toast.LENGTH_SHORT).show();
                            } else if ("54003".equals(errorCode)) {
                                Toast.makeText(context, "访问频率受限，请降低您的调用频率", Toast.LENGTH_SHORT).show();
                            } else if ("58001".equals(errorCode)) {
                                Toast.makeText(context, "译文语言方向不支持，请检查译文语言是否在语言列表里", Toast.LENGTH_SHORT).show();
                            } else if ("54004".equals(errorCode)) {
                                Toast.makeText(context, "账户余额不足，请前往管理控制台为账户充值", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }

                    @Override
                    public void onFailure(Call<TranslatedInfo> call, Throwable t) {
                        Log.d(TAG, "onFailure: " + t.toString());
                    }
                });
    }

    public void translateByGoogle(String translateText,String fromLanguage,String toLanguage ) {
        ApiRetrofit.getGoogleTranslateApi()
                .translateGoogle(translateText, fromLanguage,toLanguage)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if(response.code()!=200){
                                to.setText(response.code()+" / "+
                                        response.errorBody().string());
                                return;
                            }
                            String result = response.body().string();
                            Log.d(TAG, "translateByGoogle/ onResponse: ResponseBody--->" + result);
                            List<String> results=Utils.parseGoogleResult(result);
                            Log.d(TAG, "onResponse: Results After Parse--->"+ results.toString());
                            to.setText(results.get(0));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Log.d(TAG, "onFailure: " + t.toString());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        String chosenLanguage = data.getExtras().getString("chosenLanguage");
        Log.d(TAG, "onActivityResult: chosenLanguage---->" + chosenLanguage);
        if (!chosenLanguage.isEmpty()) {
            mChooseLanguage.setText(chosenLanguage);
        }
    }

    private void initSpinner() {
        mSpTranslateWay.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "onItemSelected: ---------Start  -----------");
                String engine = context.getResources().getStringArray(R.array.translateEngine)[position];
                Log.d(TAG, "onItemSelected: SelectedEngine--->" + engine);
                switch (position){
                    case 0:
                        //百度
                        SpUtils.setTranslateEngine(TranslateActivity.this,BAIDU);
                        break;
                    case 1:
                        //谷歌
                        SpUtils.setTranslateEngine(TranslateActivity.this,GOOGLE);
                        break;
                }
                Log.d(TAG, "onItemSelected: Engine After Selected---->"+SpUtils.getTranslateEngine(TranslateActivity.this));

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Log.d(TAG, "onNothingSelected: ---------Start  -----------");
            }
        });
    }



}
